﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Linq;
using System.IO;

namespace Scoreboard.Model
{
	public class ExternalUserDataContainer
	{
		public const string PhotoFilePath = "http://ws/hr/Valstaff%20Images/";
		public const string LoginNamePrefix = "SYNAPSE\\";
		public const string UserDataKey = "UserData";

		private static ExternalUserDataContainer _current = new ExternalUserDataContainer();
				
		private XElement _users;

		private ExternalUserDataContainer()
		{
			var entitiesContainer = new EntitiesContainer();
			var userDataProperty = entitiesContainer.Properties.Where(p => p.Key == UserDataKey).Single();

			var data = userDataProperty.Value;			
			_users = XElement.Parse(data);
		}		

		public static ExternalUserDataContainer Current
		{
			get
			{
				return _current;
			}
		}

		public User GetUser(string login)
		{
			var userElement = _users
				.Descendants(XName.Get("user"))
				.Where(e => (LoginNamePrefix + e.Attribute(XName.Get("loginname")).Value).ToUpper() == login.ToUpper())
				.SingleOrDefault();
			if (userElement == null)
			{
				return null;
			}

			var firstName = userElement.Attribute(XName.Get("firstnamer")).Value;
			var lastName = userElement.Attribute(XName.Get("lastnamer")).Value;
			var email = userElement.Attribute(XName.Get("workemail")).Value;
			var photoFileName = userElement.Attribute(XName.Get("photofilename")).Value;
			var employeeId = userElement.Attribute(XName.Get("employeeid")).Value;


			var user = new User
				{
					Login = login,
					FriendlyName = string.Format("{0} {1}", firstName, lastName),
					Email = email,
					PhotoUrl = PhotoFilePath + photoFileName,
					EmployeeId = employeeId
				};			

			return user;
		}
	}
}
